/**
 * Copyright 2009 Joe LaPenna
 */

package com.googlecode.dumpcatcher.logging;

import org.apache.http.HttpResponse;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DumpcatcherUncaughtExceptionHandler implements UncaughtExceptionHandler {

    private Dumpcatcher mDumpcatcher;

    public DumpcatcherUncaughtExceptionHandler(Dumpcatcher dumpcatcher) {
        mDumpcatcher = dumpcatcher;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        try {
            String shortMessage = StackFormattingUtil.getStackMessageString(e);
            HttpResponse response = mDumpcatcher.sendCrash(//
                    shortMessage, //
                    StackFormattingUtil.getStackTraceString(e), //
                    String.valueOf(Level.SEVERE.intValue()), //
                    "exception");
            response.getEntity().consumeContent();
            int statusCode = response.getStatusLine().getStatusCode();
            switch (statusCode) {
                case 200:
                    break;
                default:
                    Logger.getLogger("DumpcatcherUncaughtExceptionHandler").log(Level.WARNING,
                            "Unable to sendCrash, status code: " + String.valueOf(statusCode));
            }
        } catch (Exception sendCrashException) {
            Logger.getLogger("DumpcatcherUncaughtExceptionHandler").log(Level.WARNING,
                    "Unable to sendCrash", sendCrashException);
        }
    }
}
